﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FanPages.Server.Services.Contracts;
using FanPages.Server.Services.Contracts.Dto;
using FanPages.Common.DataAccess;
using FanPages.Server.Repostory.EFRepository.Model;
using FanPages.Common.SearchEngine;

namespace FanPages.Server.Services
{
    public class SearchService : ISearchService
    {
        IRepository<FanItem> fanItemRepository = new EFRepository<FanItem>(new FanPagesEntities());
        IRepository<SearchResult> searchRepository;

        List<SearchResult> searchResults = new List<SearchResult>();
        FanItem currentItem;

        public SearchService()
        {
           searchRepository = new EFRepository<SearchResult>(fanItemRepository.Context);
        }
        public void Search()
        {
            List<FanItem> fanItems = fanItemRepository.GetAll().ToList();
            foreach (var item in fanItems)
            {
                currentItem = item;
                StringBuilder exceptions = new StringBuilder();
                foreach(var ex in item.SearchException)
                {
                    exceptions.Append(String.Format("-{0} ", ex.Exception));
                }
                GoogleSearch search = new GoogleSearch();
                search.SearchCompleted +=new System.EventHandler<SearchEventArgs>(search_SearchCompleted);
                search.Key = "AIzaSyAXNyZ66QycdkUq3X3b3GzPxDhxARkk7iE";
                search.CX = "005628374864706373109:vj19xcjs8dq";
                search.Num = 10;
                search.Days = 1;
                search.LastId = item.Id;
                search.Search(item.Configuration.First().SearchWords + " " + exceptions.ToString());
            }
        }

        void  search_SearchCompleted(object sender, SearchEventArgs e)
        {
            foreach (var item in e.Response.Items)
            {
                SearchResult searchResult = new SearchResult();
                searchResult.CachedId = item.CacheId ?? String.Empty;
                searchResult.DisplayLink = item.DisplayLink ?? String.Empty;
                searchResult.HtmlSnippet = item.HtmlSnippet ?? String.Empty;
                searchResult.HtmlTile = item.HtmlTitle ?? String.Empty;
                searchResult.Link = item.Link ?? String.Empty;
                searchResult.Name = String.Empty;
                searchResult.ResultDate = DateTime.Now;
                searchResult.Snippet = item.Snippet ?? String.Empty;
                searchResult.FanItemReference.EntityKey = new System.Data.EntityKey("FanPagesEntities.FanItem", "Id", e.LastId);
                searchRepository.Add(searchResult);
            }
        }        
    }
}
